package com.vivo.tasks;

import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.vivo.Utils.SysUtils;
import com.vivo.common.DatabaseContextHolder;
import com.vivo.employee.entity.ViEmployee;
import com.vivo.employee.service.ViEmployeeService;
import com.vivo.fx.sys.entity.FxUserinfo;
import com.vivo.fx.sys.service.FxUserinfoService;
import com.vivo.system.entity.SysRolePost;
import com.vivo.system.service.SysRolePostService;
import com.vivo.tasks.vivofx.Helper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 同步用户信息（信息不全的用户）
 */
@Component
public class TaskUserCom {

    @Autowired
    private ViEmployeeService viEmployeeService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private SysRolePostService rolePostService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private FxUserinfoService fxUserinfoService;

    /**
     * 同步一下用户信息，从用户信息侧进行查找没有的用户
     */
    public void sync() {
        syncNonUserVe();
    }

    private void syncNonUserVe() {
        System.out.println("开始进行查找登录信息不完整的用户。。。");
        List<ViEmployee> veList = viEmployeeService.findYxtList();
        for (ViEmployee ve:veList) {
            saveUserInfoByVe(ve);
        }

        System.out.println("结束查找登录信息不完整的用户！共添加新用户" + veList.size() + "个！");
    }


    private void saveUserInfoByVe(ViEmployee viEmployee) {
        do {
            Office comp = officeService.get(viEmployee.getComp().getId());
            Office topComp = officeService.getTopComp(comp);
            String zone = topComp.getName().contains("安徽") ? "ah" : "js";

            FxUserinfo sysUser = null;
            User user = null;
            try {
                //  添加用户登陆信息
                user = systemService.getUserByEmpId(viEmployee.getId());
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }

            try {
                // 根据区域切换数据库
                Helper.changeDB(zone);

                sysUser = fxUserinfoService.getByEmpId(viEmployee.getId());
            } finally {
                DatabaseContextHolder.setMainDb();
            }

            if (sysUser == null) {
                continue;
            }

            if (user != null && sysUser.getUserid().equals(user.getId())) {
                continue;
            }


            // 替换用户的ID信息， 包括如下信息
            // 用户ID修改， 用户菜单ID修改， 用户角色iD修改，用户权限ID修改
            if (user != null) {
                user.setNewUid(sysUser.getUserid());
                user.setOldUid(user.getId());

                // 更新用户数据
                systemService.updVivoUser(user);
                continue;
            }

            // 获取职位对应角色
            SysRolePost rolePost = new SysRolePost();
            Role role = null;
            rolePost.setPost(viEmployee.getPostName());
            List<SysRolePost> rolePostList = rolePostService.findList(rolePost);
            if (rolePostList.size() > 0) {
                role = rolePostList.get(0).getRole();
            } else {
//                rolePost.setPost("无角色");
//                rolePostList = rolePostService.findList(rolePost);
//                if (rolePostList.size() > 0) {
//                    role = rolePostList.get(0).getRole();
//                }
                role = systemService.getRoleByName("无角色");
            }

            String password = "123456";
            if (viEmployee.getTelephone().length() == 11) {
                password = viEmployee.getTelephone().substring(5, 11);
            }
            System.out.println("password is :" + password);

            user = new User();
            user.setPassword(SystemService.entryptPassword(password));
            // 优信通同步密码和盐
            user.setSysSalt(SysUtils.createSalt());
            user.setSysPwd(SysUtils.getPwdBySalt(password, user.getSysSalt()));

//                    user.setEmployeeId(fe.getEmployeeid());
            user.setOffice(viEmployee.getDept());
            user.setPosition(viEmployee.getPost());
            user.setCompany(viEmployee.getComp());
            user.setMobile(viEmployee.getTelephone());
            user.setPhone(viEmployee.getTelephone());
            user.setLoginName(viEmployee.getTelephone());
            user.setName(viEmployee.getName());
            user.setNo(viEmployee.getCode());
            user.setEmployeeId(viEmployee.getId());
            user.setId(sysUser.getUserid());
            user.setIsNewRecord(true);
            user.setIsTaskInsert(true);

            try {
                if (role != null) {
                    user.setRole(role);
                    List<Role> rl = new ArrayList<Role>();
                    rl.add(role);
                    user.setRoleList(rl);
                }
                systemService.saveUser(user);

                // 设置用户角色
                if (role != null) {
                    systemService.assignUserToRole(role, user);
                }
            } catch (Exception e) {
                viEmployee.setErrMsg(e.getMessage());
                e.printStackTrace();
            }
        } while (false);
    }
}
